<template>

  <div style="display: flex">

    <a-space direction="vertical" size="large" :style="{width: '500px',marginLeft:'50px',marginTop: '10px'}"
             :model="form"  @submit="handleSubmit">
      <a-form :model="form" layout="vertical">
      <!--账号-->
      <a-form-item
              direction="vertical"
              field="userName" hide-asterisk="true" label="账号"
                   :rules="[{required:true,message:'必须填写账号'},
                         {minLength:4,message:'账号长度最少4个字符'},
                         {maxLength:12,message:'账号长度不能超过12个字符'}]"
                   :validate-trigger="['change','input']"
                   validate-trigger="blur"
      >
        <a-input v-model="form.userName" placeholder="请输入你的账号"/>
      </a-form-item>
      <!--密码-->
      <a-form-item
              direction="vertical"
              field="userPassword" hide-asterisk="true" label="密码"
                   :rules="[{required:true,message:'必须填写密码'},
                         {minLength:6,message:'密码长度最少6个字符'},
                         {maxLength:12,message:'密码长度最长12个字符'}]"
                   :validate-trigger="['change','input']"
                   validate-trigger="blur">
        <a-input-password v-model="form.userPassword" placeholder="请输入密码"/>
      </a-form-item>
      <!--邮箱-->
      <a-form-item
              direction="vertical"
              field="email" hide-asterisk="true" label="邮箱"
                   :rules="[{required:true,message:'必须填写邮箱'}]"
                   :validate-trigger="['change','input']"
                   validate-trigger="blur"
                   type="email"
      >
        <a-input v-model="form.email" placeholder="请输入你的邮箱"
        />
      </a-form-item>
      <!--学校-->
      <a-form-item
              direction="vertical"
              field="school" hide-asterisk="true" label="学校名称"
                   :rules="[ {maxLength:20,message:'学校名称长度最长20个字符'}]"
                   :validate-trigger="['change','input']"
                   validate-trigger="blur">
        <a-input v-model="form.school" placeholder="请输入你的学校"
        />
      </a-form-item>
      <!--年龄-->
      <a-form-item field="age" label="年龄" hide-asterisk="true"
                   :rules="[{required:false}]"

      >
        <a-input-number v-model="form.age" :min="1" :max="150" :default-value="form.age" :style="{width:'70px'}"
                        placeholder="请输入年龄"></a-input-number>

      </a-form-item>

      <!--性别-->
      <a-form-item  label="性别">
        <a-radio-group v-model="form.gender">
          <a-radio value="0" default-checked>男</a-radio>
          <a-radio value="1">女</a-radio>
        </a-radio-group>
      </a-form-item>


     <a-form-item>
       <a-button style="margin-left: 100%" size="large" shape="round" @click="updateInfo" type="primary">更新个人信息</a-button>
     </a-form-item>

      </a-form>
    </a-space>



    <!--头像-->
    <a-space direction="vertical" :style="{ width: '400px',height: '500px' }" >
      <a-upload
              action="http://47.113.195.180:8081/api/get/url"
              :fileList="file ? [file] : []"
              :show-file-list="false"
              @change="onChange"
              @progress="onProgress"
              @success="onSuccess"
      >

        <template #upload-button>
          <div
                  :class="`arco-upload-list-item${file && file.status === 'error' ? ' arco-upload-list-item-error' : ''}`"
          >
            <div class="arco-upload-list-picture custom-upload-avatar" v-if="file && file.url">

              <img :src="file.url" />
              <div class="arco-upload-list-picture-mask">
                <IconEdit />
              </div>
              <!--上传进度-->
              <a-progress
                      v-if="file.status === 'uploading' && file.percent < 100" :percent="file.percent" type="circle"
                      size="small"
                      :style="{position: 'absolute', left: '50%',top: '50%',transform: 'translateX(-50%) translateY(-50%)',}"
              />
            </div>

            <div class="arco-upload-picture-card" v-else>
              <div class="arco-upload-picture-card-text">
                <IconPlus />
                <div style="margin-top: 10px; font-weight: 600">上传头像</div>
              </div>
            </div>

          </div>
        </template>
      </a-upload>
    </a-space>


  </div>



</template>


<script setup>
  import {ref, computed} from "@vue/reactivity";
  import { watch } from 'vue';
  import myAxios from "../plugins/myAxios";
  import {useRoute} from "vue-router";
  import {useRouter} from "vue-router";
  import {reactive} from 'vue';
  import message from "@arco-design/web-vue/es/message";
  import {onMounted} from "@vue/runtime-core";
  import {routes} from "@/router/routes";
  import {getCurrentUser} from "@/services/user";
  import axios from "axios";

  const route=useRoute()

  const currentUser = ref({})
  onMounted(async () => {
    currentUser.value = await getCurrentUser();
  })

  const form = reactive({
    userName: '',
    userPassword: '',
    email: '',
    age: 18,
    school: '',
    gender: '',
    avatarUrl: '',
  });
  watch(()=>currentUser, (newValue, oldValue) => {

    if(newValue?.value){
      currentUser.value=newValue.value

    }
  }, {immediate:true,deep: true})

  const file = ref();
  const onChange = (_, currentFile) => {
    file.value = {
      ...currentFile,
    };
  };

  //文件上传成功后，onSuccess返回后端的阿里OSS的Url
  const onSuccess=(res)=>{
    form.avatarUrl=res.response?.data
  }

  //上传进度
  const onProgress = (currentFile) => {
    file.value = currentFile;
  };

  //更新个人信息
  const updateInfo=async () => {

    const res = await myAxios.post('/user/update', {
      id: currentUser?.value?.id?currentUser?.value?.id:undefined,
      username: form.userName,
      userPassword: form.userPassword,
      email: form.email,
      school: form.school,
      age: form.age,
      gender: form.gender,
      avatarUrl: form.avatarUrl,
    })

    if (res.code === 0) {
      message.success("更新成功！")
      const redirectUrl = route.query?.redirect ? route.query.redirect : '/base';

      setTimeout(() => {
        window.location.href = redirectUrl
      }, 500);

    } else {
      message.error(res.description?`${res.description}`:'更新失败！')
    }


  }

</script>
<style scoped>
  .arco-upload-picture-card {
    display: flex;
    min-width: 180px;
    height: 180px;
    margin-bottom: 0;
    margin-left: 300px;

  }

  .arco-upload-list-picture {
    display: flex;
    min-width: 180px;
    height: 180px;
    margin-bottom: 0;
    margin-left: 300px;
  }


  element.style {
  }

   .arco-upload-list-picture-mask {

     line-height: 180px;

   }



</style>